package sysAuth

import grails.converters.JSON
import initConfig.SysInitData
import sysUtil.ResultCode
import sysUtil.ResultJson
import sysUtil.SysCommUtil
import xdInterface.XdControllerInterface
import xdTool.XdWidgetReport

import java.text.SimpleDateFormat

class FunctionController implements XdControllerInterface {

    def authUtilsService

    def index() {
        query()
    }

    @Override
    def delete() {
        del()
    }
    @Override
    def detail() {
        return null
    }

    @Override
    def del() {
        return null
    }

    @Override
    def edit() {
        return null
    }

    @Override
    def save() {
        return null
    }

    @Override
    def update() {
        functionUpdate()
    }

    @Override
    def add() {
        return null
    }

    @Override
    def dowLoad() {
        return null
    }

    @Override
    def upLoad() {
        return null
    }

    @Override
    def query() {
        def result = ResultJson.resultMap()
        try {

            def list = authUtilsService.listFunctionTreeData(params)
            //println list
            result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
            result.put(ResultJson.MSG.name,ResultCode.OPT_SUCCESS.message)
            result.put(ResultJson.DATA.name,list)
        }catch (Exception e){
            result.put(ResultJson.CODE.name,ResultCode.QUERY_ERROR.code)
            result.put(ResultJson.MSG.name,ResultCode.QUERY_ERROR.message)
            e.printStackTrace()
        }finally{
            render  result as JSON
        }
    }

    @Override
    def getOne() {
        return null
    }


    /**
     * 新增更新菜单
     * @return
     */
    def functionUpdate(){
        def result = ResultJson.resultJson()
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss:SSS");
        try {
            def flag = params?.flag
            def field = params?.field
            def value = params?.value
            def id = params?.id
            def funcNo = params.funcNo?:formatter.format(new Date());
            def path = params.path?:""
            def funcName = params.name?:"New:${formatter.format(new Date())}"
            def icon = params.icon?:"layui-icon-list"
            def state = params.state?:"1"
            def orderNum = params.orderNum?Integer.parseInt(params.orderNum):1
            def parent = params.parentId?:null
            def userNo = params.userNo
            def mobile = Integer.parseInt(params.mobile?:"0")

            //缺少一个菜单本身拥有对操作权限
            def operations = params.operations?:"detail"

            def userGrade = authUtilsService.isAvailable(SysUsers?.findByUserNo(userNo))

            if(flag=="del" && id){
                def sysfunc = SysFunctions.get(Long.parseLong(id))

                if(sysfunc.getFuncNo().toUpperCase().indexOf("SYS_")!=-1 && !SysInitData.USER_GRADE_ADMIN_FUNC.contains(userGrade) && !sysfunc.creator.equals(userNo)){
                    result.put(ResultJson.CODE.name, ResultCode.OPT_NOT_AUTH.code)
                    result.put(ResultJson.MSG.name, ResultCode.OPT_NOT_AUTH.message)
                }else {
                    sysfunc.delete(flush: true)
                    result.put(ResultJson.CODE.name, ResultCode.TABLE_DATA_SUCCESS.code)
                    result.put(ResultJson.MSG.name, ResultCode.TABLE_DATA_SUCCESS.message)
                }
            }else if( field && id){

                def oldFunction = SysFunctions.get(Long.parseLong(id))
                def existsFunc = null
                if(["funcNo","path"].contains(field)){//如果更新的是编号 和 报表路径
                    existsFunc = SysFunctions.find {
                        eq(field,value)
                    }
                }

                if(existsFunc && oldFunction.id != existsFunc.id){
                    result.put(ResultJson.CODE.name, ResultCode.EXISTS_ERROR.code)
                    result.put(ResultJson.MSG.name, ResultCode.EXISTS_ERROR.message)
                }else if(oldFunction.getFuncNo().indexOf("SYS_")!=-1  && !SysInitData.USER_GRADE_ADMIN_FUNC.contains(userGrade) && oldFunction.creator != userNo){
                    //只有管理员、拥有着 ，才能更新 SYS_标记为系统菜单，非操作员不能操作
                    result.put(ResultJson.CODE.name, ResultCode.OPT_NOT_AUTH.code)
                    result.put(ResultJson.MSG.name, ResultCode.OPT_NOT_AUTH.message)
                }else{

                    if(field =="orderNum"){
                        value = Integer.parseInt(value)
                    }
                    oldFunction.setUpdater(params.updater)
                    oldFunction.setProperty(field,value)
                    oldFunction.save(flush: true)

                    result.put(ResultJson.CODE.name, ResultCode.TABLE_DATA_SUCCESS.code)
                    result.put(ResultJson.MSG.name, ResultCode.TABLE_DATA_SUCCESS.message)
                }

            } else if(!id){
                def a = new SysFunctions(
                        operations:operations,
                        creator:userNo,
                        updater:userNo,
                        path:path,
                        parentId:parent,
                        orderNum:orderNum,
                        icon:icon,
                        state:state,
                        mobile:mobile,
                        funcName:funcName,
                        funcNo:funcNo.toUpperCase())
                a.save(flush: true)
                def aa = SysCommUtil.copyMap(a)
                //println aa
                aa.put("pId",a?.parentId)
                aa.put("name",a.getFuncName())
                aa.put("id",a.id)
                aa.remove("parent")
                result.put(ResultJson.DATA.name, aa)
                result.put(ResultJson.CODE.name, ResultCode.TABLE_DATA_SUCCESS.code)
                result.put(ResultJson.MSG.name, ResultCode.TABLE_DATA_SUCCESS.message)
            }
        }catch (Exception e){
            result.put(ResultJson.CODE.name, ResultCode.QUERY_ERROR.code)
            result.put(ResultJson.MSG.name, ResultCode.QUERY_ERROR.message)
            e.printStackTrace()
        }finally{
            //println result
            render result.toString()
        }
    }




    /**
     * 根据用户权限获取所有菜单-用于菜单维护
     * @return
     */
    def getFunctionByUserAuth() {
        def result = ResultJson.resultJson()
        try {

            def list = authUtilsService.listFunctionByUserAuth(params)
            def results  =  SysCommUtil.domainListToList(list)

            result.put(ResultJson.DATA.name, results)
            result.put(ResultJson.CODE.name, ResultCode.TABLE_DATA_SUCCESS.code)
            result.put(ResultJson.MSG.name, ResultCode.TABLE_DATA_SUCCESS.message)
        } catch (Exception e) {
            result.put(ResultJson.CODE.name, ResultCode.QUERY_ERROR.code)
            result.put(ResultJson.MESSAGE.name, ResultCode.QUERY_ERROR.message)
            e.printStackTrace()
        } finally {
            //println(  result.toString() )
            render result.toString()
        }
    }

    /**
     * 获取菜单已配置操作
     * @return
     */
    def listFuncOperate(){
        def result = ResultJson.resultJson()
        try {
            def list = authUtilsService.listFuncOperate( params?.funcId)
            result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
            result.put(ResultJson.DATA.name, list)
            result.put(ResultJson.MSG.name, ResultCode.TABLE_DATA_SUCCESS.message)
        }catch (Exception e){
            result.put(ResultJson.CODE.name, ResultCode.QUERY_ERROR.code)
            result.put(ResultJson.MSG.name, ResultCode.QUERY_ERROR.message)
            e.printStackTrace()
        }finally{
            //println result
            render result.toString()
        }
    }

    /**
     * 更新：菜单拥有对操作按钮
     */
    def updateFuncOperate(){
        def result = ResultJson.resultJson()
        try {
            def  functionId = params.functionId
            def  operateId = params.operateId
            def actions = params.actions?:""
            def state = Integer.parseInt( params.state?:'0')
            def sysFunOpt =SysFunOpt.findByFunctionAndOperate(SysFunctions.get(functionId),SysOperations.get(operateId))
            if(sysFunOpt){
                sysFunOpt.setAction(actions)
                sysFunOpt.setState(state)
                sysFunOpt.save(flush: true)
            }else{
                sysFunOpt = new SysFunOpt(
                        function: SysFunctions.get(functionId),
                        operate:  SysOperations.get(operateId),
                        action: actions,
                        state: state
                )
                sysFunOpt.save(flush: true)
            }

            result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
            //result.put(ResultJson.DATA.name, sysFunOpt)
            result.put(ResultJson.MSG.name, ResultCode.TABLE_DATA_SUCCESS.message)
        }catch (Exception e){
            result.put(ResultJson.CODE.name, ResultCode.QUERY_ERROR.code)
            result.put(ResultJson.MSG.name, ResultCode.QUERY_ERROR.message)
            e.printStackTrace()
        }finally{
            // println result
            render result.toString()
        }
    }

    /**
     * 根据用户获取菜单按钮权限
     * @return
     */
    def getFuncOptsByAuth(){
        def result = ResultJson.resultJson()
        try {

            def buttonAuth = authUtilsService.getFuncOptsByAuth(params)
            result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
            result.put(ResultJson.MSG.name,ResultCode.TABLE_DATA_SUCCESS.message)
            result.put(ResultJson.DATA.name,buttonAuth)
        }
        catch (Exception e){
            result.put(ResultJson.CODE.name,ResultCode.QUERY_ERROR.code)
            result.put(ResultJson.MSG.name,ResultCode.QUERY_ERROR.message)
            e.printStackTrace()
        }finally{
            render result
        }
    }


    /**
     * 根据用户获取菜单按钮权限
     * @return
     */
    def getFuncOptsByAuthList(){
        def result = ResultJson.resultJson()
        try {

            def buttonAuth = authUtilsService.getFuncOptsByAuthList(params)
            result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
            result.put(ResultJson.MSG.name,ResultCode.TABLE_DATA_SUCCESS.message)
            result.put(ResultJson.DATA.name,buttonAuth)
        }
        catch (Exception e){
            result.put(ResultJson.CODE.name,ResultCode.QUERY_ERROR.code)
            result.put(ResultJson.MSG.name,ResultCode.QUERY_ERROR.message)
            e.printStackTrace()
        }finally{
            render result
        }
    }

    /**
     * 获取菜单已关联的rpt信息
     * @return
     */
    def getFuncCfgRptInfo(){
        def result = ResultJson.resultJson()
        try {

            def funcId = Long.parseLong(params.funcId)
            def searchStr = params.searchStr?:""
            SysFunctions sysFunctions = SysFunctions.get(funcId)
            def notCfgRpt
            def cfgRpt
            if(sysFunctions){
                cfgRpt = XdWidgetReport.get(sysFunctions?.rptId)

                if(searchStr){
                    notCfgRpt = XdWidgetReport.findAllByIdNotEqualAndNameLike(sysFunctions?.rptId,"%${searchStr}%",[offset:0,max:20])
                }else{
                    notCfgRpt = XdWidgetReport.findAllByIdNotEqual(sysFunctions?.rptId,[offset:0,max:20])
                }

            }
            result.put("cfgRpt",SysCommUtil.copyMap(cfgRpt))
            result.put(ResultJson.DATA.name,SysCommUtil.copyMapList(notCfgRpt))

            result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
            result.put(ResultJson.MSG.name,ResultCode.TABLE_DATA_SUCCESS.message)

        }
        catch (Exception e){
            result.put(ResultJson.CODE.name,ResultCode.QUERY_ERROR.code)
            result.put(ResultJson.MSG.name,ResultCode.QUERY_ERROR.message)
            e.printStackTrace()
        }finally{
            render result
        }
    }

    /**
     * 给菜单，关联rpt
     * @return
     */
    def funcAddRpt(){
        def result = ResultJson.resultJson()
        try {

            def funcId = Long.parseLong(params.funcId)
            def rptId = Long.parseLong(params.rptId)
            SysFunctions sysFunctions = SysFunctions.get(funcId)
            XdWidgetReport xdWidgetReport = XdWidgetReport.get(rptId)
            if(sysFunctions && xdWidgetReport){

                if(sysFunctions.funcNo.indexOf("SYS_") != -1){
                    result.put(ResultJson.CODE.name,ResultCode.OPT_SYS_AUTH.code)
                    result.put(ResultJson.MSG.name,ResultCode.OPT_SYS_AUTH.message)
                }else{
                    sysFunctions.setRptId(rptId)
                    sysFunctions.setFuncName(xdWidgetReport.name)
                    sysFunctions.setPath("xdWidget/report.gsp")
                    sysFunctions.save(flush: true)

                    result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
                    result.put(ResultJson.MSG.name,ResultCode.TABLE_DATA_SUCCESS.message)
                }
            }else{
                result.put(ResultJson.CODE.name,ResultCode.NOT_EXISTS_ERROR.code)
                result.put(ResultJson.MSG.name,ResultCode.NOT_EXISTS_ERROR.message)
            }
        }
        catch (Exception e){
            result.put(ResultJson.CODE.name,ResultCode.QUERY_ERROR.code)
            result.put(ResultJson.MSG.name,ResultCode.QUERY_ERROR.message)
            e.printStackTrace()
        }finally{
            render result
        }
    }
}
